import {
  Component, ElementRef, Input, OnChanges, OnDestroy,  SimpleChanges,
  ViewChild
} from '@angular/core';


import { GetRTDataByKKSCodesService} from '../../../services/get-rtdata-by-kkscodes.service'

@Component({
  selector: 'app-chart-runninghour-status',
  templateUrl: './chart-runninghour-status.component.html',
  styleUrls: ['./chart-runninghour-status.component.css','../../../../../assets/css/button.css']
})
export class ChartRunninghourStatusComponent implements OnDestroy ,OnChanges {
  ngOnChanges(changes: SimpleChanges): void {
    this.totalKks=changes['totalKks'].currentValue;
    this.time=changes['time']?changes['time'].currentValue:this.time;
    this.initChart()
  }

  constructor(
    private getKksRes:GetRTDataByKKSCodesService
  ) { }

  public componentName='runningHourPie'
  @Input() public totalKks:string;
  @Input() public time:string;
  @Input() public initData:Array<any>
  @Input() public title:string;
  // @ViewChild('chart') public chartEl: ElementRef;  //highcharts
  public chartOptions
  public _chart: any; //highcharts
  public initChart() {
    let initData = this.initData;
    this.getKksRes.getRestKksByComponent(this.componentName,this.time)
      .subscribe(
        res=>{
          // console.log('xx');
          let kksString=res.map(item=>{
            return this.totalKks+item;
          })
          let timeRange:number;
          switch (this.time){
            case 'day':timeRange=1;break;
            case 'week':timeRange=7;break;
            case 'month':timeRange=30;break;
            case 'year':timeRange=365;break;
            default:timeRange=1;break;
          }
          let time = new Date();
          let endTime=new Date(time.getFullYear(),time.getMonth(),time.getDate(),0,0,1).getTime();
          let startTime=endTime-24*3600*1000*timeRange;
          //现在只是时间是day的时候，时间范围改变时间参数和算法要变
          this.getKksRes.getKKSData(kksString,startTime,endTime)
            .subscribe(
              res=>{
                // console.log('饼图KDM数据')
                // console.log(res)
                let pieData=[];
                kksString.forEach(str=>{
                  res.RTDataSets.forEach(item=>{
                    if(item.kksCode==str){
                      let v=0;
                      item.RTDataValues.forEach(it=>{
                        v+=it.Value;
                      })
                      pieData.push(v)
                    }
                  })
                });
                if(pieData.length==initData.length){
                  initData.forEach((obj,index)=>{
                    obj.y=pieData[index];
                  })
                }
                this.fillChart(initData);
              }
            )
        }
      )
  }

  public fillChart(data?:any){
    let title = this.title;
    let opts: any = {
      chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie',
        backgroundColor: 'transparent',
        renderTo: ''
      },
      legend: {
        enabled: false
      },
      credits: {
        enabled: false
      },
      exporting: {
        enabled: false
      },
      title: {
        text: title,
        style: {
          fontSize: 'small',
        }
      },
      tooltip: {
        pointFormat: '{point.percentage:.1f}%</b>'
      },
      plotOptions: {
        pie: {
          allowPointSelect: true,
          cursor: 'pointer',
          dataLabels: {
            enabled: false,
          }
        }
      },
      series: [{
        name: 'Brands',
        colorByPoint: true,
        data: data,
      }]
    }
    this.chartOptions = opts
  }
  public ngOnDestroy() {
    if(this._chart)
      this._chart.destroy();
  }
}

